
import 'dart:async';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'package:fluwx/src/method_channel/fluwx_platform_interface.dart';
import 'package:tobias/tobias.dart';

import '../../../common_ui/loading.dart';
import '../../../repository/sjx_api.dart';

class TaskPayViewModel with ChangeNotifier {
  final VoidCallback? refreshHandle;
  bool _isLoading = true;
  double _price = 0.0;
  double _availableAmount = 0.0;
  // 支付方式选择
  bool _isAlipaySelected = true;
  bool _isWechatSelected = false;

  // 抵扣选择
  bool _isDeductSelected = true;
  bool _isNotDeductSelected = false;

  bool get isLoading => _isLoading;
  double get price => _price;
  double get availableAmount => _availableAmount;
  bool get isAlipaySelected => _isAlipaySelected;
  bool get isWechatSelected => _isWechatSelected;
  bool get isDeductSelected => _isDeductSelected;
  bool get isNotDeductSelected => _isNotDeductSelected;

  Fluwx fluwx = Fluwx();
  StreamSubscription<WeChatResponse>? _paymentSubscription;
  BuildContext? _currentContext; // 保存当前上下文

  set isLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  TaskPayViewModel({this.refreshHandle});

  void initWechatPay (BuildContext context) {
    _currentContext = context;
    fluwx.registerApi(appId: "wx1ee7dd4dd17efe54", universalLink: "https://d7ad3d64167ec6ebe08e7778f93af005.share2dlink.com/");
    _paymentSubscription = FluwxPlatform.instance.responseEventHandler.listen((response) {
      print('收到微信支付响应: ${response.toString()}');
      _handleWechatPaymentResponse(response);
    });
  }

  // 处理微信支付响应
  void _handleWechatPaymentResponse(WeChatResponse response) {
    if (_currentContext == null) return;

    if (response is WeChatPaymentResponse) {
      switch (response.errCode) {
        case 0:
        // 支付成功
          _paySuccess(_currentContext!);
          break;
        case -1:
        // 支付失败
          _payFailed(_currentContext!, '支付失败: ${response.errStr}');
          break;
        case -2:
        // 用户取消
          _showCancelMessage(_currentContext!);
          break;
        default:
        // 其他错误
          _payFailed(_currentContext!, '支付异常: ${response.errStr}');
          break;
      }
    }
  }

  void cancelSub() {
    // 取消支付监听
    _paymentSubscription?.cancel();
  }

  Future<void> getAccount() async {
    _availableAmount = await SJXApi.instance().userAccount();
    _isLoading = false;
    notifyListeners();
  }

  // 计算支付金额
  void priceAmount(String amount) {
    // 解析金额字符串（去掉￥符号）
    String cleanedAmount = amount.replaceAll('¥', '');
    _price = double.tryParse(cleanedAmount.trim()) ?? 0.0;
    notifyListeners();
  }

  // 计算实际支付金额
  double get actualAmount {
    if (_isDeductSelected) {
      if (_price <= _availableAmount) {
        return 0.0;
      } else {
        return _price - _availableAmount;
      }
    } else {
      return _price;
    }
  }

  // 计算抵扣金额
  double get deductAmount {
    if (_isDeductSelected) {
      if (_price <= _availableAmount) {
        return _price;
      } else {
        return _availableAmount;
      }
    } else {
      return 0.0;
    }
  }

  void onAlipaySelected() {
    _isAlipaySelected = true;
    _isWechatSelected = false;
    notifyListeners();
  }

  void onWechatSelected() {
    _isAlipaySelected = false;
    _isWechatSelected = true;
    notifyListeners();
  }

  void onDeductSelected() {
    _isDeductSelected = true;
    _isNotDeductSelected = false;
    notifyListeners();
  }

  void onNotDeductSelected() {
    _isDeductSelected = false;
    _isNotDeductSelected = true;
    notifyListeners();
  }

  void onPayPressed(BuildContext context, String taskId) async {
    final result = await showOkCancelAlertDialog(
      context: context,
      title: "确认支付",
      message: '实际支付金额：￥${actualAmount.toStringAsFixed(2)}',
      okLabel: "支付",
      cancelLabel: "取消",
    );
    if (result == OkCancelResult.ok) {
      Loading.showLoading();
      //判断抵扣金额是不是为0
      if (_isDeductSelected && actualAmount == 0) {
        //走余额抵扣
        await SJXApi.instance().payBalance(deductAmount, taskId);
        _paySuccess(context);
      } else {
        //判断是不是支付宝支付
        if (_isAlipaySelected) {
          Response response = await SJXApi.instance().alipayOrder(deductAmount, taskId);
          await _handleAlipay(response.data, context, taskId);
        } else {
          //微信支付
          Response response = await SJXApi.instance().wechatOrder(deductAmount, taskId);
          await _handleWechatPay(response.data, context, taskId);
        }
        // _paySuccess(context);
      }
      Loading.dismissAll();
    }
  }

  // 处理微信支付
  Future<void> _handleWechatPay(dynamic responseData, BuildContext context, String taskId) async {
    try {
      // 假设后端返回的数据结构包含微信支付所需参数
      final String appId = 'wx1ee7dd4dd17efe54';
      final String partnerId = responseData['partnerid'] ?? '';
      final String prepayId = responseData['prepayid'] ?? '';
      final String packageValue = responseData['packageValue'] ?? '';
      final String nonceStr = responseData['noncestr'] ?? '';
      final int timeStamp = int.parse(responseData['timestamp']);
      final String sign = responseData['sign'] ?? '';

      // 验证必要参数
      if (appId.isEmpty || partnerId.isEmpty || prepayId.isEmpty ||
          packageValue.isEmpty || nonceStr.isEmpty || sign.isEmpty) {
        throw Exception('获取微信支付信息失败，参数不完整');
      }

      // 检查微信是否安装
      bool isWeChatInstalled = await fluwx.isWeChatInstalled;
      if (!isWeChatInstalled) {
        _showWeChatNotInstalledDialog(context);
        return;
      }

      // 创建微信支付请求
      final success = await fluwx.pay(which: Payment(
          appId: appId,
          partnerId: partnerId,
          prepayId: prepayId,
          packageValue: packageValue,
          nonceStr: nonceStr,
          timestamp: timeStamp,
          sign: sign));
      print('调起支付结果: $success');
    } catch (e) {
      _payFailed(context, '微信支付异常: ${e.toString()}');
    }
  }

  // 显示微信未安装对话框
  void _showWeChatNotInstalledDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('未安装微信'),
        content: Text('请先安装微信App后再进行支付'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  // 处理支付宝支付
  Future<void> _handleAlipay(dynamic responseData, BuildContext context, String taskId) async {
    try {
      // 从响应中获取支付字符串
      String? orderString = responseData['orderString'];

      if (orderString == null || orderString.isEmpty) {
        throw Exception('获取支付信息失败');
      }

      Tobias tobias = Tobias();
      // 检查支付宝是否已安装
      bool isAliPayInstalled = await tobias.isAliPayInstalled;
      if (!isAliPayInstalled) {
        _showAlipayNotInstalledDialog(context);
        return;
      }
      // 使用 Tobias 进行支付
      final Map? result = await tobias.pay(orderString);
      // 处理支付结果
      _handleAlipayResult(result, context, taskId);

    } catch (e) {
      _payFailed(context, '支付异常: ${e.toString()}');
    }
  }

// 处理支付宝支付结果
  void _handleAlipayResult(Map? result, BuildContext context, String taskId) {
    if (result == null) {
      _payFailed(context, '支付结果为空');
      return;
    }

    // Tobias 返回的结果格式
    final String resultStatus = result['resultStatus']?.toString() ?? '';
    final String memo = result['memo']?.toString() ?? '';
    final String resultStr = result['result']?.toString() ?? '';

    print('支付宝支付结果: resultStatus=$resultStatus, memo=$memo');

    switch (resultStatus) {
      case '9000':
      // 支付成功
        _paySuccess(context);
        break;
      case '8000':
      // 支付处理中
        _showProcessingDialog(context, taskId);
        break;
      case '6001':
      // 用户取消
        _showCancelMessage(context);
        break;
      case '6002':
      // 网络连接出错
        _payFailed(context, '网络连接出错，请检查网络后重试');
        break;
      case '4000':
      // 支付失败
        _payFailed(context, '支付失败，请重试');
        break;
      default:
      // 未知状态
        _handleUnknownStatus(context, resultStatus, memo, taskId);
        break;
    }
  }

  // 显示支付宝未安装对话框
  void _showAlipayNotInstalledDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('未安装支付宝'),
        content: Text('请先安装支付宝App后再进行支付'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  // 显示处理中对话框
  void _showProcessingDialog(BuildContext context, String taskId) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('支付处理中'),
        content: Text('支付结果确认中，请稍后在订单列表中查看支付状态'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              Navigator.pop(context); // 返回上一页
            },
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  // 处理未知状态
  void _handleUnknownStatus(BuildContext context, String resultStatus, String memo, String taskId) {
    if (memo.contains('成功') || memo.contains('success')) {
      _paySuccess(context);
    } else {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('支付状态未知 ($resultStatus)'),
          content: Text('支付结果不明确: $memo\n建议联系客服确认是否支付成功'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text('好的'),
            ),
          ],
        ),
      );
    }
  }

// 显示取消消息
  void _showCancelMessage(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('用户取消支付'),
        backgroundColor: Colors.orange,
      ),
    );
  }

// 支付失败处理
  void _payFailed(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('支付失败: $message'),
        backgroundColor: Colors.red,
      ),
    );
  }

  void _paySuccess(BuildContext context) {
    // 显示支付成功提示
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('支付成功'),
        backgroundColor: Colors.green,
      ),
    );

    // 回调刷新处理
    refreshHandle?.call();

    // 延迟返回
    Future.delayed(Duration(milliseconds: 1500), () {
      // if (widget.isAddTask) {
      //   _goBackToTaskFabuManager(context);
      // } else {
        Navigator.pop(context);
      // }
    });
  }

  void _goBackToTaskFabuManager(BuildContext context) {
    // 寻找TaskFabuManager页面并返回
    Navigator.popUntil(context, (route) => route.isFirst);
  }

}